#!/usr/bin/env node
'use strict';

require('shelljs/global');

let fs = require( 'fs' ),
    config = require( '../config/config.json');

module.exports = {
    'checkPath': function( relaPath ){

        if( relaPath === 'undefined' ){
            return {
                status: 'error',
                msg: 'Error: please input path or folder name.'
            }
        }else{

            let absoPath;

            try{
                absoPath = fs.realpathSync( relaPath );
            }catch( err ){
                absoPath = false;
            }

            if( absoPath === false ){
                return {
                    'msg': `Warning: ${relaPath} is not exist, continue to create it.`,
                    'status': 'warning',
                };
            }else{
                let canAccess = this.checkPathAccess( absoPath, relaPath );
                if( canAccess.status === 'error'  ){
                    return canAccess
                }else{
                    if( this.checkEmpty(absoPath) ){
                        return {
                            'status': 'success'
                        }
                    }else{
                        return {
                            'status': 'warning',
                            'msg': `Warning: ${relaPath} is not empty, continue may be have a clash.`
                        }
                    }
                }
            }

        }
    },

    'checkPathAccess': function( absoPath, relaPath ){
        let canAccess;

        try{
            canAccess = fs.accessSync( absoPath, fs.R_OK | fs.W_OK );
        }catch( err ){
            canAccess = false;
        }

        if( canAccess === false ){
            return {
                'msg': `Error: permission denied, access '${relaPath}'`,
                'status': 'error'
            };
        }else{
            let stat = fs.statSync( absoPath );
            if( stat.isDirectory() ){
                return {
                    'status': 'success'
                };
            }else{
                return {
                    'msg': `Error: ${relaPath} is not a folder`,
                    'status': 'error'
                };
            }
        }
    },

    'checkEmpty': function( absoPath ){
        let dir = fs.readdirSync( absoPath );
        // accept empty folder or folder only have hidden files.
        if( dir.every( i => (i[0] === '.') )){
            return true;
        }else{
            return false;
        }
    },

    'checkEnv': function(){
        let need = []
        config.envRequireList.forEach(function( item ){
            if( ! which( item ) ){
                need.push( item );
            }
        });
        if( need.length === 0 ){
            return { 'lack': false };
        }else{
            return { 'lack': true, msg: `Error: WorkFlow need ${need.join(', ')}.` };
        }
    },

    'create': function( file, data ){
        fs.writeFileSync( file, data );
    }
}
